package vip.specimen.system.common.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import vip.specimen.system.utils.CommonUtil;
import vip.specimen.system.common.component.RedisComponent;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

@Component
@Slf4j
public class RequestCountFilter implements Filter {
    @Resource
    private RedisComponent redis;
    @Value("${system.prefix.request}")
    private String requestPrefix;
    @Value("${system.decollator}")
    private String decollator;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(servletRequest, servletResponse);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestMethod = request.getMethod();
        String requestUrl = request.getRequestURL().toString();
        String ipAddress = CommonUtil.getIp(request);
        HashMap<String, Object> map = new HashMap<>();
        map.put("ipAddress", ipAddress);
        map.put("requestMethod", requestMethod);
        map.put("requestUrl", requestUrl);
        map.put("time", String.valueOf(System.currentTimeMillis()));
        map.put("User-Agent", request.getHeader("User-Agent"));
        redis.hset(requestPrefix + decollator + requestMethod, ipAddress, map);
    }

    @Override
    public void destroy() {

    }
}
